<template>
  <div class="member-list-page">
    <ElCard shadow="never">
      <template #header>
        <div class="card-header">
          <span>会员列表</span>
          <div class="right-tools">
            <ElInput v-model="query.keyword" placeholder="搜索昵称/手机/邮箱" clearable style="width:240px" @keyup.enter.native="onSearch" />
            <ElButton @click="onSearch">查询</ElButton>
            <ElButton @click="openInvite()">邀请记录</ElButton>
          </div>
        </div>
      </template>
      <ElTable :data="tableData" v-loading="loading" border>
        <ElTableColumn prop="id" label="ID" width="80" align="center" />
        <ElTableColumn prop="nickname" label="昵称" min-width="160" />
        <ElTableColumn prop="mobile" label="手机" width="140" />
        <ElTableColumn prop="email" label="邮箱" min-width="200" />
        <ElTableColumn prop="gradeName" label="级别" width="120" />
        <ElTableColumn label="状态" width="120" align="center">
          <template #default="{ row }">
            <ElSwitch :model-value="row.status === 1" @change="(v:boolean)=>onStatus(row,v)" />
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="360" align="center" fixed="right">
          <template #default="{ row }">
            <ElButton size="small" @click="onView(row)">查看</ElButton>
            <ElButton size="small" @click="onEdit(row)">编辑</ElButton>
            <ElButton size="small" @click="onPassword(row)">密码</ElButton>
            <ElPopconfirm title="确认删除该会员？" @confirm="() => onDelete(row)">
              <template #reference>
                <ElButton size="small" type="danger">删除</ElButton>
              </template>
            </ElPopconfirm>
          </template>
        </ElTableColumn>
      </ElTable>

      <div class="table-footer">
        <ElPagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="query.pageSize"
          :current-page="query.page"
          @current-change="onPageChange"
        />
      </div>
    </ElCard>

    <!-- 查看/编辑弹窗 -->
    <ElDialog v-model="dialog.visible" :title="dialog.title" width="640px">
      <ElForm :model="form" ref="formRef" label-width="88px">
        <ElFormItem label="昵称">
          <ElInput v-model="form.nickname" :readonly="dialog.readonly" />
        </ElFormItem>
        <ElFormItem label="手机">
          <ElInput v-model="form.mobile" :readonly="dialog.readonly" />
        </ElFormItem>
        <ElFormItem label="邮箱">
          <ElInput v-model="form.email" :readonly="dialog.readonly" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="dialog.visible=false">关 闭</ElButton>
        <ElButton v-if="!dialog.readonly" type="primary" :loading="submitLoading" @click="onSubmitEdit">保 存</ElButton>
      </template>
    </ElDialog>

    <!-- 密码弹窗 -->
    <ElDialog v-model="pwdDialog.visible" title="设置密码" width="460px">
      <ElForm :model="pwdForm" ref="pwdFormRef" label-width="88px">
        <ElFormItem label="新密码">
          <ElInput v-model="pwdForm.password" type="password" show-password />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="pwdDialog.visible=false">取 消</ElButton>
        <ElButton type="primary" :loading="submitLoading" @click="onSubmitPassword">确 定</ElButton>
      </template>
    </ElDialog>

    <!-- 邀请记录抽屉 -->
    <ElDrawer v-model="inviteDrawer.visible" title="邀请记录" size="50%">
      <ElTable :data="inviteDrawer.list" v-loading="inviteDrawer.loading" border>
        <ElTableColumn prop="id" label="ID" width="80" align="center" />
        <ElTableColumn prop="inviter" label="邀请人" min-width="140" />
        <ElTableColumn prop="invitee" label="被邀请人" min-width="140" />
        <ElTableColumn prop="createdAt" label="时间" min-width="180" />
      </ElTable>
    </ElDrawer>

  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { memberService } from '@/api/memberApi'

interface MemberItem {
  id: number
  nickname: string
  mobile?: string
  email?: string
  gradeName?: string
  status: number
}

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<MemberItem[]>([])
const total = ref(0)
const query = reactive({ page: 1, pageSize: 10, keyword: '' })

const dialog = reactive({ visible: false, title: '查看', readonly: true })
const formRef = ref<FormInstance>()
const form = reactive<Partial<MemberItem>>({})

const pwdDialog = reactive({ visible: false })
const pwdFormRef = ref<FormInstance>()
const pwdForm = reactive<{ id?: number; password: string }>({ id: undefined, password: '' })

const inviteDrawer = reactive<{ visible: boolean; loading: boolean; list: any[]; userId?: number }>({
  visible: false,
  loading: false,
  list: []
})

async function fetchList() {
  loading.value = true
  try {
    const res: any = await memberService.memberList({ page: query.page, pageSize: query.pageSize, keyword: query.keyword })
    tableData.value = (res?.data?.list ?? res?.data ?? []) as MemberItem[]
    total.value = Number(res?.data?.total ?? tableData.value.length)
  } finally {
    loading.value = false
  }
}

function onSearch() {
  query.page = 1
  fetchList()
}

function onView(row: MemberItem) {
  dialog.visible = true
  dialog.title = '查看'
  dialog.readonly = true
  Object.assign(form, row)
}

function onEdit(row: MemberItem) {
  dialog.visible = true
  dialog.title = '编辑'
  dialog.readonly = false
  Object.assign(form, row)
}

async function onSubmitEdit() {
  submitLoading.value = true
  try {
    await memberService.memberEdit(form as any)
    ElMessage.success('保存成功')
    dialog.visible = false
    fetchList()
  } finally {
    submitLoading.value = false
  }
}

function onPassword(row: MemberItem) {
  pwdDialog.visible = true
  pwdForm.id = row.id
  pwdForm.password = ''
}

async function onSubmitPassword() {
  if (!pwdForm.id || !pwdForm.password) return
  submitLoading.value = true
  try {
    await memberService.memberPassword({ id: pwdForm.id, password: pwdForm.password })
    ElMessage.success('密码已更新')
    pwdDialog.visible = false
  } finally {
    submitLoading.value = false
  }
}

async function onDelete(row: MemberItem) {
  await memberService.memberDelete({ id: row.id })
  ElMessage.success('删除成功')
  fetchList()
}

async function onStatus(row: MemberItem, v: boolean) {
  await memberService.memberStatus({ id: row.id, status: v ? 1 : 0 })
  ElMessage.success('状态已更新')
  fetchList()
}

async function openInvite(userId?: number) {
  inviteDrawer.visible = true
  inviteDrawer.loading = true
  inviteDrawer.userId = userId
  try {
    const res: any = await memberService.memberInviteList(userId ? { userId } : {})
    inviteDrawer.list = (res?.data?.list ?? res?.data ?? []) as any[]
  } finally {
    inviteDrawer.loading = false
  }
}

function onPageChange(p: number) {
  query.page = p
  fetchList()
}

onMounted(fetchList)
</script>

<style scoped>
.member-list-page .card-header{display:flex;align-items:center;justify-content:space-between}
.member-list-page .right-tools{display:flex;gap:8px}
.table-footer{padding:12px 0;display:flex;justify-content:flex-end}
</style>


